package club.banyuan;

import club.banyuan.util.Constant;
import club.banyuan.util.PropUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class UserService {
    private int idCount = 1;
    private List<User> userList = new ArrayList<>();
    private static final UserService INSTANCE = load();

    private UserService() {
    }

    //Getter and Setter


    public int getIdCount() {
        return idCount;
    }

    public void setIdCount(int idCount) {
        this.idCount = idCount;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public static UserService getINSTANCE() {
        return INSTANCE;
    }


    //保存
    private void save() {
        String rlt = JSONObject.toJSONString(this);
        try (FileOutputStream fileOutputStream = new FileOutputStream(PropUtil.getProp(Constant.Prop.USER_STORE))) {
            fileOutputStream.write(rlt.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //加载用户信息
    private static UserService load() {
        try (FileInputStream inputStream = new FileInputStream(PropUtil.getProp(Constant.Prop.USER_STORE))) {
            return JSONObject.parseObject(inputStream, StandardCharsets.UTF_8, UserService.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new UserService();
    }

    //检校用户信息
    public User userLogin(User user) {
        for (User one : userList) {
            if (one.getUsername().equals(user.getUsername())
                    && one.getPassword().equals(user.getPassword())) {
                return one;
            }
        }
        return null;
    }

    public void addUser(User user) {
        Optional<User> any = userList.stream()
                .filter(t -> t.getUsername().equals(user.getUsername()))
                .findAny();
        if (any.isPresent()) {
            System.out.println("用户已存在");
        }
        user.setId(idCount++);
        userList.add(user);
        save();
    }

    public void updateUser(User user) {
        User old = getUser(user.getId());
        old.setUsername(user.getUsername());
        old.setPassword(user.getPassword());
        old.setRolename(user.getRolename());
        save();
    }

    // 删除用户
    public void deleteUser(int id) {
        // OK
        // Iterator<User> iterator = userList.iterator();
        // while (iterator.hasNext()) {
        //   if (iterator.next().getId() == id) {
        //     iterator.remove();
        //   }
        // }

        // 简写
        userList.removeIf(user -> user.getId() == id);

        // 错误代码
        // for (User user : userList) {
        //   if (user.getId() == id) {
        //     userList.remove(user);
        //   }
        // }
        save();
    }

    public User getUser(int id) {
        for (User user : userList) {
            if (user.getId() == id) {
                return user;
            }
        }
        throw new BadRequestException("用户不存在 id:" + id);
    }

    public List<User> getRowsList(int page, int rows, String name) {
        List<User> searchList;
        if (name == null || name.equals("")) {
            searchList = getUserList();
        } else {
            searchList = userList.stream().filter(t ->
                    t.getUsername().contains(name)).collect(Collectors.toList());
        }

        int total = searchList.size();
        List<User> rowsList = new ArrayList<>();

        int allPages = (int) Math.ceil(total * 1.0 / rows);
        System.out.println(allPages);
        UserService userService = HttpServer.getUserService();
        if (allPages <= 1) {
            return searchList;
        }
        for (int i = 8 * (page - 1), j = 0; i < userService.getUserList().size() && j < 8; i++, j++) {
            rowsList.add(userService.getUserList().get(i));
        }
        return rowsList;
    }

    public static void main(String[] args) {
        UserService userService = new UserService();
        User user = new User();
        user.setUsername("a");
        user.setPassword("123");
        user.setRolename("admin");
        userService.addUser(user);

    }


}